package fragment;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.NetworkImageView;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.sql.Date;
import java.text.SimpleDateFormat;
import java.util.ArrayList;

import bean.NewsBean;
import bean.WeatherBean;
import utils.RequestQueueUtils;
import zhang.automobileservice.GasStationActivity;
import zhang.automobileservice.MycarActivity;
import zhang.automobileservice.NewsConsultActivity;
import zhang.automobileservice.NewsDetialActivity;
import zhang.automobileservice.R;
import zhang.automobileservice.WashCarActivity;
import zhang.automobileservice.activity.firstpagedetial.MaintainActivity;
import zhang.automobileservice.activity.firstpagedetial.SecondCarActivity;
import zhang.automobileservice.activity.firstpagedetial.WayConditionActivity;

/**
 * Created by Administrator on 2016/7/18.
 */
public class FirstpageFragment extends Fragment implements View.OnClickListener {
    private ImageView iv_illegalserch;
    private ImageView iv_gasstation;
    private ImageView iv_carwash;
    private ImageView iv_waycondition;
    private RelativeLayout rl_carsecond;
    private RelativeLayout rl_maintain;
    private ListView lv_newslist;
    private ImageView iv_title;
    private TextView tv_more;
    private ArrayList<String> arrayList;
    private NetworkImageView weather_img;
    private TextView tv_city;
    private TextView weather;
    private TextView tv_temperature;
    private TextView wash_car;
    private TextView tv_updateTime;
    private ArrayList<NewsBean> newList;
    WeatherBean weatherBean = new WeatherBean();
    String city = "";

    //声明AMapLocationClient类对象
    public AMapLocationClient mLocationClient = null;
    //声明mLocationOption对象
    public AMapLocationClientOption mLocationOption = null;
    //声明定位回调监听器
    public AMapLocationListener mLocationListener = new AMapLocationListener() {
        @Override
        public void onLocationChanged(AMapLocation amapLocation) {
            if (amapLocation != null) {
                if (amapLocation.getErrorCode() == 0) {
                    //Log.e("======", "amapLocation.getDistrict()");
                    //定位成功回调信息，设置相关消息
                    amapLocation.getLocationType();//获取当前定位结果来源，如网络定位结果，详见定位类型表
                    amapLocation.getLatitude();//获取纬度
                    amapLocation.getLongitude();//获取经度
                    amapLocation.getAccuracy();//获取精度信息
                    /*SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    Date date = new Date(amapLocation.getTime());
                    df.format(date);//定位时间*/
                    //Log.e("=====getAddress", amapLocation.getProvince());
                   // Log.e("======++",   amapLocation.getLatitude()+"|||"+amapLocation.getLongitude());
                    amapLocation.getAddress();//地址，如果option中设置isNeedAddress为false，则没有此结果，网络定位结果中会有地址信息，GPS定位不返回地址信息。
                    amapLocation.getCountry();//国家信息
                    amapLocation.getProvince();//省信息
                    city = amapLocation.getCity();//城市信息
                    amapLocation.getDistrict();//城区信息
                    amapLocation.getStreet();//街道信息
                    amapLocation.getStreetNum();//街道门牌号信息
                    amapLocation.getCityCode();//城市编码
                    amapLocation.getAdCode();//地区编码
                    amapLocation.getAoiName();//获取当前定位点的AOI信息
                } else {
                    //显示错误信息ErrCode是错误码，errInfo是错误信息，详见错误码表。
                    Log.e("AmapError", "location Error, ErrCode:"
                            + amapLocation.getErrorCode() + ", errInfo:"
                            + amapLocation.getErrorInfo());
                }
                Message message = new Message();
                message.what=0x002;
                message.obj = amapLocation.getCity();
                handler.sendMessage(message);
            }

        }
    };
    Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if(msg.what==0x002){
                city = (String) msg.obj;
            }
            initData();
        }
    };
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_firstpage, null);
        initView(view);
        getAddress();
        lv_newslist.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Intent intent = new Intent(getActivity(), NewsDetialActivity.class);
                Bundle bundle = new Bundle();
                bundle.putSerializable("NewsBean", newList.get(position));
                intent.putExtras(bundle);
                startActivity(intent);
            }
        });
        return view;
    }


    private void getAddress() {
        //初始化定位
        mLocationClient = new AMapLocationClient(getContext());
//设置定位回调监听
        mLocationClient.setLocationListener(mLocationListener);
        //初始化定位参数
        mLocationOption = new AMapLocationClientOption();
//设置定位模式为高精度模式，Battery_Saving为低功耗模式，Device_Sensors是仅设备模式
        mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
//设置是否返回地址信息（默认返回地址信息）
        mLocationOption.setNeedAddress(true);
//设置是否只定位一次,默认为false
        mLocationOption.setOnceLocation(true);

        if (mLocationOption.isOnceLocationLatest()) {
            mLocationOption.setOnceLocationLatest(true);
//设置setOnceLocationLatest(boolean b)接口为true，启动定位时SDK会返回最近3s内精度最高的一次定位结果。
//如果设置其为true，setOnceLocation(boolean b)接口也会被设置为true，反之不会。
        }

//设置是否强制刷新WIFI，默认为强制刷新
        mLocationOption.setWifiActiveScan(true);
//设置是否允许模拟位置,默认为false，不允许模拟位置
        mLocationOption.setMockEnable(false);
//设置定位间隔,单位毫秒,默认为2000ms
        mLocationOption.setInterval(50000000);
//给定位客户端对象设置定位参数
        mLocationClient.setLocationOption(mLocationOption);
//启动定位
        mLocationClient.startLocation();
    }

    private void initData() {
        String url = "http://api.dagoogle.cn/news/get-news?tableNum=4";
        RequestQueueUtils.exectueJsonRequest(getActivity(), url, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject jsonObject) {
                try {
                    if ("200".equals(jsonObject.getString("status"))) {
                        JSONArray array = jsonObject.getJSONArray("data");
                        arrayList = new ArrayList();
                        newList = new ArrayList<NewsBean>();
                        for (int i = 0; i < array.length(); i++) {
                            String title = array.getJSONObject(i).getString("title");
                            NewsBean news = new NewsBean();
                            JSONObject o = (JSONObject) array.get(i);
                            news.setNews_id(o.getString("news_id"));
                            news.setTop_image(o.getString("top_image"));
                            news.setReply_count(o.getString("reply_count"));
                            news.setEdit_time(o.getString("edit_time"));
                            news.setTitle(o.getString("title"));
                            news.setContent(o.getString("content"));
                            news.setSource(o.getString("source"));
                            newList.add(news);
                            arrayList.add(title);
                        }
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                ArrayAdapter<String> adapter = new ArrayAdapter<String>(getContext(), R.layout.firstfragment_listitem, R.id.tv_arrayList, arrayList);
                lv_newslist.setAdapter(adapter);

            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {

            }
        });
        String weatherUrl = "http://route.showapi.com/9-2?showapi_appid=20077&showapi_sign=c23cae77a0db4753867830987143bbf1&area="+city;
        RequestQueueUtils.exectueJsonRequest(getActivity(), weatherUrl, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject o) {
                try {
                    if("0".equals(o.getString("showapi_res_code"))){
                        JSONObject jsonObject = o.getJSONObject("showapi_res_body");
                        JSONObject object = jsonObject.getJSONObject("now");
                        JSONObject object1  =jsonObject.getJSONObject("f1");
                        weatherBean.setWeather_pic(object.getString("weather_pic"));
                        weatherBean.setDay( object1.getString("day"));
                        weatherBean.setWeather( object.getString("weather"));
                        weatherBean.setDay_air_temperature( object1.getString("day_air_temperature"));
                        weatherBean.setNight_air_temperature( object1.getString("night_air_temperature"));
                        weatherBean.setWeekday( object1.getInt("weekday")+"");
                        weatherBean.setWeather_code(object.getString("weather_code"));
                        weatherBean.setTemperature_time( object.getString("temperature_time"));
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                setView();
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {

            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_illegalserch:
                Intent intent = new Intent(getActivity(), MycarActivity.class);
                startActivity(intent);
                break;
            case R.id.iv_gasstation:
                Intent intent1 = new Intent(getActivity(), GasStationActivity.class);
                startActivity(intent1);
                break;
            case R.id.iv_carwash:
                Intent intent2 = new Intent(getActivity(), WashCarActivity.class);
                startActivity(intent2);
                break;
            case R.id.iv_waycondition:
                Intent intent3 = new Intent(getActivity(), WayConditionActivity.class);
                startActivity(intent3);
                break;
            case R.id.rl_carsecond:
                Intent intent4 = new Intent(getActivity(), SecondCarActivity.class);
                startActivity(intent4);
                break;
            case R.id.rl_maintain:
                Intent intent5 = new Intent(getActivity(), MaintainActivity.class);
                startActivity(intent5);
                break;
            case R.id.tv_more:
                Intent intent6 = new Intent(getActivity(), NewsConsultActivity.class);
                startActivity(intent6);
                break;

        }

    }

    private void initView(View view) {
        iv_illegalserch = (ImageView) view.findViewById(R.id.iv_illegalserch);
        iv_gasstation = (ImageView) view.findViewById(R.id.iv_gasstation);
        iv_carwash = (ImageView) view.findViewById(R.id.iv_carwash);
        iv_waycondition = (ImageView) view.findViewById(R.id.iv_waycondition);
        rl_carsecond = (RelativeLayout) view.findViewById(R.id.rl_carsecond);
        rl_maintain = (RelativeLayout) view.findViewById(R.id.rl_maintain);
        lv_newslist = (ListView) view.findViewById(R.id.lv_newslist);

        iv_illegalserch.setOnClickListener(this);
        iv_gasstation.setOnClickListener(this);
        iv_carwash.setOnClickListener(this);
        iv_waycondition.setOnClickListener(this);
        rl_carsecond.setOnClickListener(this);
        rl_maintain.setOnClickListener(this);

        iv_title = (ImageView) view.findViewById(R.id.iv_title);
        iv_title.setOnClickListener(this);
        tv_more = (TextView) view.findViewById(R.id.tv_more);
        tv_more.setOnClickListener(this);
        weather_img = (NetworkImageView) view.findViewById(R.id.weather_img);
        weather_img.setOnClickListener(this);
        tv_city = (TextView) view.findViewById(R.id.tv_city);
        tv_city.setOnClickListener(this);
        weather = (TextView) view.findViewById(R.id.weather);
        weather.setOnClickListener(this);
        tv_temperature = (TextView) view.findViewById(R.id.tv_temperature);
        tv_temperature.setOnClickListener(this);
        wash_car = (TextView) view.findViewById(R.id.wash_car);
        wash_car.setOnClickListener(this);
        tv_updateTime = (TextView) view.findViewById(R.id.tv_updateTime);
        tv_updateTime.setOnClickListener(this);
    }

    private void setView(){
        String weekday = null;
        RequestQueueUtils.exectueNetWorkImageView(getActivity(),weatherBean.getWeather_pic(),weather_img);
        switch (weatherBean.getWeekday()){
            case "1":
                weekday="星期一";
                break;
            case "2":
                weekday="星期二";
                break;
            case "3":
                weekday="星期三";
                break;
            case "4":
                weekday="星期四";
                break;
            case "5":
                weekday="星期五";
                break;
            case "6":
                weekday="星期六";
                break;
            case "7":
                weekday="星期日";
                break;


        }
        tv_city.setText(weatherBean.getDay().substring(4,6)+"/"+weatherBean.getDay().substring(6,8)+"  "+weekday);
        weather.setText(weatherBean.getWeather());
        tv_temperature.setText(weatherBean.getNight_air_temperature()+"°C-"+weatherBean.getDay_air_temperature()+"°C");
        tv_updateTime.setText(weatherBean.getTemperature_time()+"更新");
    }
}
